package com.rd.teacher.jichao.day13;

public class TestTicket implements Runnable {
    // 假设有100张票
    volatile int ticketsNum = 100;

    //  TestTicket ticket = new TestTicket();
    //  Thread t1 = new Thread(ticket);
    //  Thread t2 = new Thread(ticket);
    //  Thread t3 = new Thread(ticket);

    // 因为在创建线程时  我们传进去的是同一个ticket对象
    // 所以多个线程共享ticketsNum
    // 所以多个线程共享obj
    // 这是一个被多线程共享的对象
    // 这个Object只是加锁使用时使用的对象
    Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //  synchronized (this)
//            synchronized (obj) {
                if (ticketsNum <= 0) {
                    System.out.println("票买光了");
                    return;
                }

                System.out.println(Thread.currentThread().getName() +
                        " 出票：" + ticketsNum);
                ticketsNum--;
//            }
        }
    }

    public static void main(String[] args) {
        TestTicket ticket = new TestTicket();
        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);
        Thread t4 = new Thread(ticket);
        Thread t5 = new Thread(ticket);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
